<template>
  <div class="page-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-select
        v-model="searchForm.status"
        placeholder="请选择工单状态"
        style="width: 200px; margin-right: 10px"
      >
        <el-option label="待处理" value="0" />
        <el-option label="处理中" value="1" />
        <el-option label="已完成" value="2" />
      </el-select>
      <el-button type="primary" @click="loadData">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 表格 -->
    <el-card class="table-card" shadow="never" :loading="loading">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold',
          height: '50px',
        }"
        :cell-style="{
          padding: '12px 0',
        }"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column
          prop="description"
          label="报修描述"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="imageUrl"
          label="图片"
          width="100"
          align="center"
        >
          <template #default="scope">
            <el-image
              :src="`http://localhost:8080${scope.row.imageUrl}`"
              width="100"
              height="100"
              :preview-src-list="[`http://localhost:8080${scope.row.imageUrl}`]"
              :initial-index="0"
              fit="cover"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="handlerName"
          label="处理人"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="handlerPhone"
          label="处理人电话"
          min-width="120"
          align="center"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="160"
          align="center"
        />
        <el-table-column
          prop="finishTime"
          label="完成时间"
          min-width="160"
          align="center"
        />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === 1
                  ? 'warning'
                  : scope.row.status === 2
                  ? 'primary'
                  : 'success'
              "
            >
              {{
                scope.row.status === 1
                  ? "待处理"
                  : scope.row.status === 2
                  ? "处理中"
                  : "已完成"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              处理
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑 -->
    <el-dialog v-model="dialogVisible" title="编辑" width="500px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="报修描述" prop="description">
          <span style="font-weight: bold; color: red">{{
            form.description
          }}</span>
        </el-form-item>
        <el-form-item label="处理人" prop="handlerId">
          <el-select v-model="form.handlerId" placeholder="请选择处理人">
            <el-option
              v-for="item in handlerList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待处理" :value="1" :disabled="true" />
            <el-option label="处理中" :value="2" :disabled="form.status === 2 || form.status === 3" />
            <el-option label="已完成" :value="3" :disabled="form.status === 3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { pageRequest, editRequest, delRequest } from "../../api/repair"
import { pageRequest as getHandlerListRequest } from "../../api/users"

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const handlerList = ref<any>([])

// 搜索表单
const searchForm = reactive({
  status: "",
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref("add")
const formRef = ref()
const form = reactive({
  id: null,
  handlerId: null,
  status: null,
  description: null,
})

// 加载表格数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      ...searchForm,
    }
    const res: any = await pageRequest(params)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error("加载数据失败:", error)
    ElMessage.error("加载数据失败")
  } finally {
    loading.value = false
  }
}

/* 获取所有维修人员 */
const getHandlerList = async () => {
  const res: any = await getHandlerListRequest({ role: 2 })
  if (res.code === 200) {
    handlerList.value = res.data.records.map((item: any) => ({
      label: item.username,
      value: item.id,
    }))
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.status = ""
  currentPage.value = 1
  loadData()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 清空表单
const resetForm = () => {
  form.id = null
  form.handlerId = null
  form.status = null
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 编辑工单
const handleEdit = (row: any) => {
  dialogType.value = "edit"
  dialogVisible.value = true
  resetForm()
  Object.assign(form, row)
}

// 删除工单
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该工单吗？删除后不可恢复！", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(async () => {
      try {
        await delRequest(row.id)
        ElMessage.success("删除成功")
        loadData()
      } catch (error:any) {
        console.error("删除失败:", error)
        ElMessage.error(error.response?.data?.msg || "删除失败")
      }
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  try {
    const { handlerId, status, id } = form
    if (!handlerId) {
      ElMessage.error("请选择处理人")
      return
    }
    if (!status) {
      ElMessage.error("请选择状态")
      return
    }
    await editRequest({ handlerId, status, id })
    ElMessage.success("更新成功")
    dialogVisible.value = false
    loadData()
  } catch (error: any) {
    console.error("更新失败:", error)
    ElMessage.error(error?.response?.data?.msg)
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
  getHandlerList()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  height: 100%;
  background-color: #f5f7fa;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  border-radius: 4px;
}
</style>
